

package com.zx.config.jackson;

import com.zx.dto.response.Response;
import com.zx.config.exception.BaseBusinessException;
import com.zx.config.exception.SysError;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: ServerExceptionResolver
 * @Author: zhou hang
 * @CreateTime: 2015-07-17 11:16
 */
public class ServerExceptionResolver extends AbstractHandlerExceptionResolver {

    private ObjectMapper objectMapper;

    private String contentType;

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                              Exception ex) {
        PrintWriter pw = null;
        try {
            logger.error(String.format("ServerExceptionResolver [ex:%s][url====>:%s][paramenter===>:%s]",
                    ex.getMessage(), request.getRequestURI(), objectMapper.writeValueAsString(request.getParameterMap())), ex);

            response.setContentType(JacksonObjectMapper.contentType);
            response.setStatus(HttpServletResponse.SC_OK);
            pw = response.getWriter();
            Response re = handleException(ex);
            pw.write(JacksonObjectMapper.getInstance().writeValueAsString(re));
        } catch (IOException e) {
            logger.error(e);
        } finally {
            if (pw != null)
                pw.close();
        }
        return null;
    }

    private Response handleException(Exception ex) {
        Response response = new Response();

        if (ex instanceof BaseBusinessException) {
            BaseBusinessException bbe = (BaseBusinessException) ex;
            response.setCode(bbe.getCode());
            response.setData(bbe.getText());
        }
        else {
            response.setCode(SysError.SYSTEM_ERROR.getErrorCode());
            response.setData(SysError.SYSTEM_ERROR.getErrorMessage());
        }

        return response;
    }

    public ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }


}